#define _CRT_SECURE_NO_WARNINGS
#include "Seqlist.h"
void SLInit(SL* ps) {
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLDestroy(SL* ps) {
	if (ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLCheckCapacity(SL* ps) {
	if (ps->size == ps->capacity) {
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
		if (tmp == NULL) {
			perror("realloc fail");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
}

void SLPrint(SL* ps) {
	for (int i = 0; i < ps->size; i++)
		printf("%d ", ps->arr[i]);
	printf("\n");
}

void SLPushBack(SL* ps, SLDataType x) {
	SLCheckCapacity(ps);
	assert(ps);
	ps->arr[ps->size++] = x;
}

void SLPushFront(SL* ps, SLDataType x) {
	SLCheckCapacity(ps);
	assert(ps);
	for (int i = ps->size; i > 0; i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}

void SLPopBack(SL* ps) {
	assert(ps && ps->size);
	ps->size--;
}

void SLPopFront(SL* ps) {
	assert(ps && ps->size);
	for (int i = 0; i < ps->size - 1; i++) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

int SLFind(SL* ps, SLDataType x) {
	assert(ps);
	for (int i = 0; i < ps->size; i++) {
		if (x == ps->arr[i])
			return i;
	}
	return -1;
}

void SLInsert(SL* ps, SLDataType x, int index) {
	assert(ps);
	assert(index >= 0 && index <= ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > index; i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[index] = x;
	++ps->size;
}

void SLErase(SL* ps, int index) {
	assert(ps);
	assert(index >= 0 && index < ps->size);
	for (int i = index; i < ps->size - 1; i++) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}